<?php
/**                                          
 * 话题
 * @author M2
 * @version 1.0
 * create Date 2013-04-27
 */
class TopicModel extends Model{
	var $tableName = 'weibo_topic';
	/**
	 * 添加话题	
	 * @param string $content 话题内容
	 * @param boolean|int $weiboId 微博ID
	 * @param boolean|array $data
	 */
	function addTopic( $content, $weiboId = false, $data = false ){
		preg_match_all("/#([^#]*[^#^\s][^#]*)#/is",$content,$arr);
		$arr = array_unique($arr[1]);
		foreach($arr as $v){
			$this->addKey($v, $weiboId, $data);
		}
	}

	/**
	 * 添加话题	
	 * @param string $content 话题内容
	 * @param boolean|int $weiboId 微博ID
	 * @param boolean|array $data
	 */
	private function addKey($key, $weiboId, $data){
		$map['name'] = trim(preg_replace("/#/",'',trim($key)));
		if( $this->where($map)->count() ){
			$this->where($map)->setInc('count');
			if($weiboId) {
				$this->addWeiboJoinTopic($map['name'], $weiboId, $data, true);
			}
		}else{
			$map['count'] = 1;
			$map['ctime'] = time();
			$topicId = $this->add($map);
			if($weiboId) {
				$this->addWeiboJoinTopic($topicId, $weiboId, $data);
			}
			return $topicId;
		}
	}

	/**
	 * 添加微博与话题的关联	
	 * @param int $topicNameOrId 话题ID
	 * @param int $weiboId 微博ID
	 * @param array $data
	 * @param boolean $isExist 是否关闭
	 */
	private function addWeiboJoinTopic($topicNameOrId, $weiboId, $data, $isExist = false) {
		if($isExist) {
			$map['name'] = $topicNameOrId;
			$topicId = $this->where($map)->getField('topic_id');
		} else {
			$topicId = $topicNameOrId;
		}

		$add['weibo_id'] = $weiboId;
		$add['topic_id'] = $topicId;
		if(is_null($data['type'])) {
			$add['type'] = 0;
		} else {
			$add['type'] = $data['type'];
		}
		$add['transpond_id'] = $data['transpond_id'];
		M('weibo_topic_link')->add($add);
	}
	
	/**
	 * 删除微博与话题关联	
	 * @param string $content 话题内容
	 * @param int $weiboId 微博ID 
	 */
	public function deleteWeiboJoinTopic($content, $weiboId) {
		preg_match_all("/#([^#]*[^#^\s][^#]*)#/is", $content, $arr);
		$arr = array_unique($arr[1]);
		$map['name'] = array('IN', $arr);
		$topicIdArr = $this->field('topic_id')->where($map)->select();
		$topicIdArr = common('Array')->getSubByKey($topicIdArr, 'topic_id');
		$del['weibo_id'] = $weiboId;
		$del['topic_id'] = array('IN', $topicIdArr);
		M('weibo_topic_link')->where($del)->delete();
		foreach($arr as $v) {
			$topicMap['name'] = $v;
			$this->where($topicMap)->setDec('count');
		}
	}

	/**
	 * 获取微博与话题关联的统计数	
	 * @param int $topicId 话题ID
	 */
	public function getWeiboJoinTopicCount($topicId) {
		$map['topic_id'] = $topicId;
		$count = M('weibo_topic_link')->where($map)->count();
		return $count;
	}

	/**
	 * 获取给定话题名的话题ID
	 * @param string $name 话题名
	 * @return int 话题ID
	 */
	public function getTopicId($name){
		$map['name'] = preg_replace("/#/",'',$name);
		if (empty($map['name']))
			return 0;
		$info = $this->where($map)->find();
		if ($info['topic_id']) {
			return $info['topic_id'];
		} else {
			$map['count'] = 0;
			$map['ctime'] = time();
			return $this->add($map);
		}
	}

	/**
	 * 获取站点的热门话题.如果不指定参数range.默认是按照系统配置来计算
	 * @return array 热门话题
	 */
	public function getHot($type=null, $range=null,$limit=10){
		$hot_list = array();
		$type     = 'recommend' == $type ? 'recommend' : 'auto';
		$expire   = 1 * 3600; // 1 hour
		$range    = !$range ? $expire : intval($range);
		$cache_id = '_weibo_hot_topic_' . $type.'_'.$range;
		if ('recommend' == $type) {
			$hot_list = $this->getRecommend();
		} else if ('auto' == $type) {
			$map['count'] = array('gt', '0');
			//热门话题时间范围
			if ($range >= 1) {
				$map['ctime'] = array('gt', mktime(0,0,0,date("m"),date("d")+1,date("Y"))-$range*24*3600);
			}
			$map['status'] = 0;
			$hot_list = $this->where($map)->order('`count` DESC')->limit($limit)->select();
			/* $map['topic_id'] = array('exp','>=((SELECT MAX(topic_id) FROM yl_weibo_topic)-(SELECT MIN(topic_id) FROM yl_weibo_topic)) * RAND() + 
					(SELECT MIN(topic_id) FROM yl_weibo_topic)');
			$this->where($map)->order('count desc')->limit($limit)->select(); */
		}
		//取热度 - 按照当前值与最大值的比例计算
		$hot_counts = max(common('Array')->getSubByKey($hot_list, 'count'));
		foreach($hot_list as $k=>$v){
			$hot_list[$k]['name']	=	htmlspecialchars($v['name']);
			$hot_list[$k]['rating'] = ceil(($v['count']/$hot_counts)*100);
			$hot_list[$k]['stop'] = ($hot_list[$k]['rating']-6) > 0 ? $hot_list[$k]['rating']-6 : 0;
		}
		return $hot_list;
	}

	/**
	 * 最新话题	
	 * @param int $num 显示数量
	 */
	function getNew($num){
		return $this->order('cTime DESC')->limit($num)->select();
	}
	
	/**
	 * 获取推荐专题列表
	 */
	public function getRecommend(){
		$list = M('WeiboTopics')->field('topic.name,topic.count,topics.domain,topics.note')
								->table(C('DB_PREFIX')."weibo_topics as topics LEFT JOIN ".C('DB_PREFIX')."weibo_topic as topic ON topics.topic_id=topic.topic_id")
								->where('topics.recommend=1 AND topics.status=0')
								->order('topics.topics_id DESC')->select();
		return $list;
	}
	
	/**
	 * 获取推荐专题列表-手机
	 */
	public function getAppRecommend(){
		$list = M('WeiboTopic')->field('topic.topic_id as id,topic.name as name')
		->table(C('DB_PREFIX')."weibo_topic as topic")
		->where('topic.count>0')
		->order('topic.count DESC')->select();
		return $list;
	}
	
	/**
	 * 获取话题详细信息	
	 */
	public function getTopics($name = null, $topics_id = null, $domain = null, $recommend = false){
		if ($name) {
			$name = html_entity_decode(urldecode($name), ENT_QUOTES);
			$map['topic_id'] = $this->getTopicId($name);
		} else if($topics_id) {
			$map['topics_id'] = intval($topics_id);
		} else if ($domain) {
			$map['domain'] = $domain;
		} else {
			return false;
		}
		$map['status'] = 0;
		$topics = M('weibo_topics')->where($map)->find();
		if ($topics) {
			$topics['name'] = $name ? $name : $this->getField('name', "topic_id={$topics['topic_id']}");
		}
		return $topics;
	}
	
	/**
	 * 首页显示话题
	 */
	function getIndexNew(){
		$querysql = "SELECT t1.topic, weibo.content as weibo,u.uid,u.uname FROM 
		(SELECT t.name as topic, tl.weibo_id,t.ctime  FROM `{$this->tablePrefix}weibo_topic` as t  
		left join `{$this->tablePrefix}weibo_topic_link` as tl  on t.topic_id = tl.topic_id where t.count>2 order by t.ctime desc ) as t1
		 left join `{$this->tablePrefix}weibo` as weibo on  t1.weibo_id=weibo.weibo_id 
		 left join `{$this->tablePrefix}user` as u on weibo.uid=u.uid  order by t1.ctime desc,weibo.ctime desc";
		$res = $this->query($querysql);
		if(!empty($res)){
			$topic = "#".$res[0]['topic']."#";
			$num = 1;
			foreach($res as $k => $v){
				$res[$k]['weibo'] = str_replace($topic,'',$v['weibo'],$num);	
				$res[$k]['image'] = getUserFaceUrl($res[$k]['uid']);
			}
		}
		return $res;
	}
}
